package com.vaadin.thomas.contenttool;

import java.util.Locale;

import com.github.wolfie.blackboard.Blackboard;
import com.vaadin.thomas.contenttool.data.Model;
import com.vaadin.thomas.contenttool.exceptions.ValueNotFoundException;
import com.vaadin.thomas.contenttool.ui.events.LangChangedEvent;

/**
 * Main class for the Tool. Provides methods for fetching the translations of
 * given identifiers.
 * 
 * @author Thomas Mattsson / Vaadin Ltd.
 */
public class ContentTool {

	public static final String PREVIEW_URIFRAGMENT = "preview";

	private Config conf;

	private Locale currentLocale;
	private Blackboard bb;

	private boolean previewMode;

	public ContentTool(Config c, Locale l, Blackboard bb) {

		conf = c;
		currentLocale = l;
		this.bb = bb;
	}

	/**
	 * Gets a value for the given identifier in the language specified with
	 * {@link #setLang(Locale)}.
	 * <p>
	 * Checks for versioning and timed publishing.
	 * 
	 * @param identifier
	 * @return the localization if found; the identifier itself is returned
	 *         otherwise.
	 * @throws ValueNotFoundException
	 *             if a Value cannot be found and
	 *             {@link Config#throwWhenValueNotFound()} is set to
	 *             <code>true</code>.
	 */
	public String get(String identifier) throws ValueNotFoundException {

		if (previewMode) {
			return Model.get().getPreview().get(identifier, currentLocale);
		} else {
			return Model.get().getProduction().get(identifier, currentLocale);
		}
	}

	/**
	 * @return The current language of returned values.
	 */
	public Locale getLang() {
		return currentLocale;
	}

	/**
	 * Use this method to change the language of the returned values.
	 * 
	 * @param newLang
	 */
	public void setLang(Locale newLang) {
		if (!currentLocale.equals(newLang)) {
			currentLocale = newLang;
			bb.fire(new LangChangedEvent());
		}
	}

	/**
	 * @return The currently used {@link Config}.
	 */
	public Config conf() {
		return conf;
	}

	public String getUserNameForUI() {
		return conf.getUserNameForAdminUI(conf.getUserIdToStore());
	}

	public void setPreviewMode(boolean set) {
		previewMode = set;
	}

	public boolean isPreviewMode() {
		return previewMode;
	}
}
